#include "TextureManager.h"
#include <GL/glfw.h>

#include <cstring>

typedef TextureList::const_iterator TextureIter;

TextureManager& TextureManager::Instance() {
	static TextureManager tm;
	return tm;
}

TextureManager::~TextureManager() {
	//Make sure we free up GL memory, don't want to hog anything
	for(TextureList::iterator itr = textures.begin(); itr != textures.end(); itr++){
		glDeleteTextures(1, &(itr->second));
	}
	textures.clear();
}

unsigned int TextureManager::getTexture(const char *filename) {
	if(strlen(filename) == 0)	//stop messing around
		return (unsigned)-1;
		
	TextureList::const_iterator itr = textures.find(filename);
	if(itr == textures.end()) {
	// Did not find the texture, please load it
		unsigned int ind;
		glEnable(GL_TEXTURE_2D);
		glGenTextures(1, &ind);
		glBindTexture(GL_TEXTURE_2D, ind);
		
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);

		//Thank you glfw...		
		glfwLoadTexture2D(filename, GLFW_BUILD_MIPMAPS_BIT);
		
		glDisable(GL_TEXTURE_2D);
		textures[filename] = ind;	//save it in our map
		
		return ind;
	}
	
	return itr->second;
}

